package sg.edu.nus.iss.umpire;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.umpire.dao.EMF;
import sg.edu.nus.iss.umpire.domain.Umpire;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SecurityFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if(user == null){
			response.setContentType("text/html");
			response.getWriter().println("<table align='center'>" +
					"<tr>" +
					"<td>" +
					"<img src='/static/image/umpire.jpg'/>" +
					"</td>" +
					"<td valign='bottom'>" +
					"<h3>Welcome to Umpire Management System. <br/>Please <a href=\"" +
                    userService.createLoginURL(((HttpServletRequest)request).getRequestURI()) +
                    "\">sign in</a>.</h3>" +
                    "</td>" +
                    "</tr>" +
                    "</table>");
		} else{
			HttpServletRequest httpRequest = (HttpServletRequest)request;
			String requestURI = httpRequest.getRequestURI();
			if("/s/logout".equalsIgnoreCase(requestURI)){
				HttpServletResponse httpResponse = (HttpServletResponse)response;
				String signoutUrl = userService.createLogoutURL("/s/umpires");
				httpResponse.sendRedirect(signoutUrl);
			} else{
				 if(httpRequest.getSession().getAttribute("userSession") == null){
					 httpRequest.getSession().setAttribute("userSession", findUmpire(user));
				 }
				 
				 chain.doFilter(request, response);
			}
		}
	}
	
	private Umpire findUmpire(User user){
		
		EntityManager em = EMF.get().createEntityManager();
		try {
			Query query = em.createQuery("SELECT FROM " + Umpire.class.getName() + " umpire where umpire.email=:umpireEmail");
			query.setParameter("umpireEmail", user.getEmail());
			List<Umpire> resultList = query.getResultList();
			if(resultList.isEmpty()){
				 Umpire umpire = new Umpire();
				 umpire.setEmail(user.getEmail());
				 umpire.setName(user.getNickname());
				 em.persist(umpire);
				return umpire;
			}else{
				return resultList.get(0);
			}
		} finally {
			em.close();
		}
	}


}
